package com.fashiontextile.common.utils;

import com.fashiontextile.common.constant.TokenConstants;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.util.Map;

/**
 * @author brooke_zb
 */
@Slf4j
public class JwtUtils {
    private static JWSSigner signer = null;
    private static JWSVerifier verifier = null;
    private static final JWSHeader header = new JWSHeader(JWSAlgorithm.HS512);

    /**
     * 生成jwt
     * @return jwt
     */
    public static String createToken(Map<String, Object> payload) throws JOSEException {
        JWSObject jwt = new JWSObject(header, new Payload(payload));
        jwt.sign(signer);
        return jwt.serialize();
    }

    /**
     * 解析jwt
     * @return jwt
     */
    public static Map<String, Object> parseToken(String jwt) throws ParseException, JOSEException {
        JWSObject jwsObject = JWSObject.parse(jwt);
        if (!jwsObject.verify(verifier)) {
            throw new JOSEException("JWT Signature invalid!");
        }
        return jwsObject.getPayload().toJSONObject();
    }

    static {
        try {
            signer = new MACSigner(TokenConstants.SECRET);
            verifier = new MACVerifier(TokenConstants.SECRET);
        } catch (JOSEException e) {
            log.error("Error when initialize JwtUtils", e);
        }
    }
}
